package cn.ulric.jms.chat;

import javax.jms.*;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * @author Ulric
 */
public class Chat implements MessageListener {

    private TopicSession pubSession;
    private TopicPublisher publisher;
    private TopicConnection connection;
    private String username;

    public Chat(String topicFactory, String topicName, String username) throws Exception {
        //使用jndi.properties文件获取一个JNDI链接
        InitialContext ctx = new InitialContext();

        //查找JMS连接工厂并创建连接
        TopicConnectionFactory connectionFactory = (TopicConnectionFactory) ctx.lookup(topicFactory);
        TopicConnection connection = connectionFactory.createTopicConnection();

        //创建两个JMS会话对象
        TopicSession pubSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        TopicSession subSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

        //查找一个JMS主题
        Topic chatTopic = (Topic) ctx.lookup(topicName);

        //创建一个JMS的发布者和订阅者。createSubscriber中附加的参数是一个消息选择器（null）和noLocal标记
        //的一个真值，它表明这个发布者生产的消息不应该被它自己所消费
        TopicPublisher publisher = pubSession.createPublisher(chatTopic);
        TopicSubscriber subscriber = subSession.createSubscriber(chatTopic, null, true);

        //设置一个JMS消息侦听器
        subscriber.setMessageListener(this);

        this.connection = connection;
        this.publisher = publisher;
        this.pubSession = pubSession;
        this.username = username;
    }

    public void onMessage(Message message) {
        try {
            TextMessage textMessage = (TextMessage) message;
            System.out.println(textMessage.getText());
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

    protected void writeMessage(String text) throws JMSException {
        TextMessage message = pubSession.createTextMessage();
        message.setText(username + ":" + text);
        publisher.publish(message);
    }

    public void close() throws JMSException {
        this.connection.close();
    }

    public static void main(String[] args) {
        if(args.length != 3){
            System.out.println("Factory,Topic,or username missing");
        }
        try {
            Chat chat = new Chat(args[0],args[1],args[2]);
            BufferedReader commandLine = new BufferedReader(new InputStreamReader(System.in));
            while (true){
                String s = commandLine.readLine();
                if(s.equalsIgnoreCase("exit")){
                    chat.close();
                    System.exit(0);
                } else {
                    chat.writeMessage(s);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
